import { createRouter, createWebHistory } from 'vue-router'
import LoginView from '../views/LoginView.vue'
import Gotopassword from '../views/Gotopassword.vue'
import Gotouser from '../views/Gotouser.vue'
import MainLayout from '../components/MainLayout.vue'
import { getApiUrl } from '../config/api.js'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: LoginView,
    },
    {
      path: '/Gotopassword',
      name: 'Gotopassword',
      component: Gotopassword,
    },
    {
      path: '/Gotouser',
      name: 'Gotouser',
      component: Gotouser,
    },
    {
      path: '/dashboard',
      name: 'Dashboard',
      component: MainLayout,
      meta: { requiresAuth: true }
    },
    {
      path: '/user',
      name: 'UserManagement',
      component: MainLayout,
      meta: { requiresAuth: true }
    },
    {
      path: '/role',
      name: 'RoleManagement',
      component: MainLayout,
      meta: { requiresAuth: true }
    },
    {
      path: '/permission',
      name: 'PermissionManagement',
      component: MainLayout,
      meta: { requiresAuth: true }
    },
    {
      path: '/articles',
      name: 'Articles',
      component: MainLayout,
      meta: { requiresAuth: true }
    },
    {
      path: '/files',
      name: 'Files',
      component: MainLayout,
      meta: { requiresAuth: true }
    },
    {
      path: '/menus',
      name: 'Menus',
      component: MainLayout,
      meta: { requiresAuth: true }
    },
    {
      path: '/sys-settings',
      name: 'SystemSettings',
      component: MainLayout,
      meta: { requiresAuth: true }
    },
    {
      path: '/sys-log',
      name: 'Logs',
      component: MainLayout,
      meta: { requiresAuth: true }
    },
    {
      path: '/profile',
      name: 'Profile',
      component: MainLayout,
      meta: { requiresAuth: true }
    }
  ],
})

// 路由守卫 - 启用安全验证
router.beforeEach(async (to, from, next) => {
  const token = localStorage.getItem('token')
  console.log('路由导航:', to.path)
  console.log('Token:', token)
  
  // 如果需要认证但没有token，重定向到登录页
  if (to.meta.requiresAuth && !token) {
    console.log('需要认证但无token，重定向到登录页')
    next('/')
    return
  }
  
  // 如果有token，验证token有效性
  if (token && to.meta.requiresAuth) {
    try {
      const response = await fetch(getApiUrl('/auth/validate'), {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })
      
      if (!response.ok) {
        console.log('Token无效，清除并重定向到登录页')
        localStorage.removeItem('token')
        localStorage.removeItem('loginUsername')
        next('/')
        return
      }
    } catch (error) {
      console.log('Token验证失败，清除并重定向到登录页')
      localStorage.removeItem('token')
      localStorage.removeItem('loginUsername')
      next('/')
      return
    }
  }
  
  // 如果已登录但访问登录页，重定向到仪表盘
  if (to.path === '/' && token) {
    console.log('已登录，重定向到仪表盘')
    next('/dashboard')
    return
  }
  
  // 其他情况正常导航
  next()
})

export default router
